import datetime
import os

from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID

base_dir = os.path.dirname(os.path.abspath(__file__))


def generate_ca():
    one_day = datetime.timedelta(days=1)
    ten_day = datetime.timedelta(days=3650)
    today = datetime.datetime.today()
    yesterday = today - one_day
    tomorrow = today + ten_day

    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=4096,
        backend=default_backend()
    )
    public_key = private_key.public_key()
    builder = x509.CertificateBuilder()

    builder = builder.subject_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, 'MoYuno-from-2022-07-25'),
    ]))
    builder = builder.issuer_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, 'JetProfile CA'),
    ]))
    builder = builder.not_valid_before(yesterday)
    builder = builder.not_valid_after(tomorrow)
    builder = builder.serial_number(x509.random_serial_number())
    builder = builder.public_key(public_key)

    certificate = builder.sign(
        private_key=private_key, algorithm=hashes.SHA256(),
        backend=default_backend()
    )
    private_bytes = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption())
    public_bytes = certificate.public_bytes(
        encoding=serialization.Encoding.PEM)
    ca_path = os.path.join(base_dir, "0/ca.key")
    with open(ca_path, "wb") as fout:
        fout.write(private_bytes)
    crt_path = os.path.join(base_dir, "0/ca.crt")
    with open(crt_path, "wb") as fout:
        fout.write(public_bytes)


if __name__ == '__main__':
    generate_ca()
